#include "common.h"
#include "video_stream.h"
#include "audio_stream.h"

int main() {
    avformat_network_init();

    const char *input_streams[MAX_CAMERAS] = {
        "rtsp://admin:hanwei123@192.168.1.65/Streaming/Channels/101",
        "rtsp://admin:hanwei123@192.168.1.65/Streaming/Channels/101"
    };

    pthread_t threads[MAX_CAMERAS];

    start_zlmediakit_server_once();

    // 初始化每个摄像头的状态
    for (int i = 0; i < MAX_CAMERAS; i++) {
        pthread_mutex_init(&g_stream_states[i].mutex, NULL);
        g_stream_states[i].video_inited = 0;
        g_stream_states[i].audio_inited = 0;
        g_stream_states[i].init_completed = 0;
    }

    // 创建媒体流
    for (int i = 0; i < MAX_CAMERAS; i++) {
        char stream_id[32];
        snprintf(stream_id, sizeof(stream_id), "test%d", i);
        g_media[i] = create_stream(stream_id);
        usleep(100000);
    }

    // 为每个摄像头启动拉流线程
    for (int i = 0; i < MAX_CAMERAS; i++) {
        CameraStream* camera = malloc(sizeof(CameraStream));
        if (!camera) {
            fprintf(stderr, "Failed to allocate memory for camera %d\n", i);
            continue;
        }

        camera->input_stream = input_streams[i];
        camera->cam_id = i;

        // 创建视频线程
        if (pthread_create(&threads[i*2], NULL, pull_video_stream_thread, camera) != 0) {
            fprintf(stderr, "Failed to create video thread for camera %d\n", i);
            free(camera);
            continue;
        }

        // 创建音频线程
        if (pthread_create(&threads[i*2+1], NULL, pull_audio_stream_thread, camera) != 0) {
            fprintf(stderr, "Failed to create audio thread for camera %d\n", i);
            free(camera);
            continue;
        }

        printf("🧵 Main: Created threads for camera %d\n", i);
        usleep(200000);
    }

    printf("All streams are running. Press Ctrl+C to exit.\n");

    while (1) {
        sleep(1);
    }

    return 0;
}
